<template>
    <div class="w750" :class="themes.theme" :style="{ '--themescolor': themes.color }">
        <template v-if="!isLoad">
            <Noempty :pic="require('../../assets/images/order-empty.png')" :title="errorTitle" />
        </template>
        <template v-else>
            <div class="invoice">
                <!-- 付款后会显示订单信息 -->
                <div v-if="type == 1" class="mt-1 bg-white d-flex position-relative overflow-h p-1 rounded-15">
                    <div class="img">
                        <legend-image
                            :pic="invoiceInfo.prodImg"
                            :options="{ w: '160', h: '160' }"
                            class="w-100 h-100"
                            :isJD="invoiceInfo.prodSource == 'JD'"
                        />
                    </div>
                    <div class="d-flex flex-column j-sb font-14" style="padding: 0.1rem">
                        <div>
                            <span>订单编号：</span>
                            <span>{{ invoiceInfo.subNumber }}</span>
                        </div>
                        <div>
                            <span>开票金额：</span>
                            <span class="font-14 text-main">￥{{ invoiceInfo.invoiceAmount }}</span>
                            <van-icon class="icon font-14" name="info-o" @click="showInvoiceExplain = true" style="margin-left: 5px" />
                        </div>
                    </div>
                </div>
                <!-- 主体信息 -->
                <van-form>
                    <div class="mt-1 rounded-15 overflow-h position-relative">
                        <div
                            class="bg-white pb-2 transition-all05"
                            :style="{ 'padding-bottom': titleInfo.invTitleType == 'PERSONAL' ? '0' : '20px' }"
                        >
                            <!-- 发票类型 -->
                            <van-cell
                                title="发票类型"
                                :value="invoiceTypeVal"
                                is-link
                                value-class="font-13"
                                @click="showInvoiceTypeSelect = true"
                                :border="false"
                            />
                            <!-- 抬头类型 -->
                            <van-field
                                name="radio"
                                label="抬头类型"
                                input-align="right"
                                :border="false"
                                label-class="font-14"
                                style="font-size: 13px"
                            >
                                <template #input>
                                    <van-radio-group v-model="titleInfo.invTitleType" direction="horizontal" @change="changeTitleType">
                                        <van-radio name="PERSONAL" :checked-color="themes.color" icon-size="13px">个人或事业单位</van-radio>
                                        <van-radio name="ENTERPRISE" :checked-color="themes.color" icon-size="13px" @click="isDown = true">
                                            企业
                                        </van-radio>
                                    </van-radio-group>
                                </template>
                            </van-field>
                            <!-- 发票抬头 -->
                            <van-field
                                v-model="titleInfo.invTitle"
                                label="发票抬头"
                                :border="false"
                                input-align="right"
                                label-class="font-14"
                                style="font-size: 13px"
                                placeholder="请填写需要开具发票的企业名称"
                            >
                                <template #button>
                                    <van-icon name="arrow" class="icon" @click.self="showInvoiceTitleSelectPop" />
                                </template>
                            </van-field>
                            <!-- 税号 -->
                            <van-field
                                v-if="titleInfo.invTitleType == 'ENTERPRISE'"
                                v-model="titleInfo.invIdfctMark"
                                label="税号"
                                placeholder="纳税人识别号"
                                :border="false"
                                label-class="font-14"
                                style="font-size: 13px"
                                input-align="right"
                                clearable
                            />
                            <!-- 选择企业或专用发票才会显示 -->
                            <template v-if="(titleInfo.invTitleType == 'ENTERPRISE' && !isDown) || invoiceType == 'VAT_INVOICE'">
                                <!-- 开户银行 -->
                                <van-field
                                    v-model="titleInfo.invDepositBank"
                                    label="开户银行"
                                    :placeholder="invoiceType == 'VAT_INVOICE' ? '必填' : '选填'"
                                    label-class="font-14"
                                    style="font-size: 13px"
                                    input-align="right"
                                    clearable
                                    :border="false"
                                />
                                <!-- 银行账号 -->
                                <van-field
                                    v-model="titleInfo.invBankAccout"
                                    label="银行账号"
                                    :placeholder="invoiceType == 'VAT_INVOICE' ? '必填' : '选填'"
                                    label-class="font-14"
                                    style="font-size: 13px"
                                    input-align="right"
                                    clearable
                                    :border="false"
                                />
                                <!-- 企业地址 -->
                                <van-field
                                    v-model="titleInfo.invRegAddr"
                                    label="企业地址"
                                    :placeholder="invoiceType == 'VAT_INVOICE' ? '必填' : '选填'"
                                    label-class="font-14"
                                    style="font-size: 13px"
                                    input-align="right"
                                    clearable
                                    :border="false"
                                />
                                <!-- 企业电话 -->
                                <van-field
                                    v-model="titleInfo.invRegPhone"
                                    label="企业电话"
                                    :placeholder="invoiceType == 'VAT_INVOICE' ? '必填' : '选填'"
                                    label-class="font-14"
                                    style="font-size: 13px"
                                    input-align="right"
                                    clearable
                                    :border="false"
                                />
                            </template>
                            <!-- 设置默认抬头 -->
                            <van-field label="设置为默认抬头" label-width="2rem" :border="false" input-align="right">
                                <template #input>
                                    <van-checkbox v-model="titleInfo.defaultTitle" :checked-color="themes.color" icon-size="15px" />
                                </template>
                            </van-field>
                        </div>
                        <!-- 下拉上拉 -->
                        <div
                            v-if="titleInfo.invTitleType == 'ENTERPRISE' && invoiceType !== 'VAT_INVOICE'"
                            class="text-center bg-white"
                            style="position: absolute; bottom: 0; left: 50%; transform: translateX(-50%)"
                        >
                            <span class="iconfont" v-if="isDown" @click="isDown = false" style="font-size: 0.2rem">&#xe636;</span>
                            <span class="iconfont" style="font-size: 0.4rem" v-else @click="isDown = true">&#xe607;</span>
                        </div>
                    </div>
                    <!-- 收票人信息 -->
                    <div class="mt-1 bg-white" style="border-radius: 15px; overflow: hidden" v-if="invoiceType == 'ORDINARY_INVOICE'">
                        <van-field
                            v-model="invoiceMoblie"
                            label="收票人手机"
                            label-class="font-14"
                            style="font-size: 13px"
                            :border="false"
                            input-align="right"
                            placeholder="请填写收票人手机"
                        />
                        <van-field
                            v-model="invoiceEmail"
                            label="收票人邮箱"
                            label-class="font-14"
                            style="font-size: 13px"
                            :border="false"
                            input-align="right"
                            placeholder="请填写收票人邮箱"
                        />
                    </div>
                    <!-- 发票内容 -->
                    <div class="my-1 bg-white d-flex j-sb font-14 rounded-15 overflow-h" style="padding: 10px 16px">
                        <div>
                            <span style="margin-right: 5px">发票内容</span>
                            <van-icon class="icon" name="info-o" @click="showInvoiceContent = true" />
                        </div>
                        <div>明细</div>
                    </div>

                    <!-- 发票地址 -->
                    <div class="submit-order rounded-15 overflow-h" style="margin-bottom: 0" v-if="invoiceType !== 'ORDINARY_INVOICE'">
                        <template v-if="invoiceInfo && invoiceInfo.invAddress">
                            <div class="order-address">
                                <div @click="goAddress">
                                    <div class="user-info">
                                        <img :src="require(`@/assets/style-images/sub-local-${themes.theme}.png`)" alt="" />
                                        <em class="item">{{ invoiceInfo.invConsignee }}</em>
                                        <em class="item">{{ invoiceInfo.invPhone }}</em>
                                    </div>
                                    <div class="address-det" style="margin: 0">
                                        {{ invoiceInfo.invAddress }}
                                    </div>
                                    <i class="arr"><img src="@/assets/images/arrow.png" alt="" /></i>
                                </div>
                            </div>
                        </template>

                        <template v-else>
                            <div class="order-address">
                                <div @click="goAddress">
                                    <div class="user-info">
                                        <img :src="require(`@/assets/style-images/sub-local-${themes.theme}.png`)" alt="" />
                                        <em class="item">请添加收货地址</em>
                                        <em class="item"></em>
                                    </div>
                                    <div class="address-det"></div>
                                    <i class="arr"><img src="@/assets/images/arrow.png" alt="" /></i>
                                </div>
                            </div>
                        </template>
                    </div>

                    <div style="margin: 16px; margin-top: 60px; padding-bottom: 30px">
                        <van-button
                            @click="onSubmit"
                            round
                            block
                            type="info"
                            native-type="submit"
                            :color="themes.color"
                            style="height: 40px; font-size: 16px"
                        >
                            提交申请
                        </van-button>
                        <van-button
                            @click="goback"
                            round
                            block
                            type="info"
                            native-type="submit"
                            color="#fff"
                            style="height: 40px; font-size: 16px; margin-top: 14px"
                        >
                            <span class="text-main">{{ type == 1 ? '返回' : '不开发票' }}</span>
                        </van-button>
                    </div>
                </van-form>
            </div>
        </template>
        <!-- 发票类型选择 -->
        <van-action-sheet v-model="showInvoiceTypeSelect" title="发票类型选择" class="bg-f8" style="height: 65%">
            <div class="p-1">
                <van-radio-group v-model="invoiceType">
                    <van-cell
                        v-for="(item, index) in arrType"
                        :key="index"
                        :title="invTypeTitle(item)"
                        label="电子发票与纸质发票具有同等法律效力，可支持报销入账"
                        clickable
                        @click="selectInvoiceType(item)"
                        class="mb-1 rounded-15 overflow-h font-14"
                    >
                        <template #right-icon>
                            <van-radio :name="item" :checked-color="themes.color" icon-size="14px" />
                        </template>
                    </van-cell>
                </van-radio-group>
            </div>
        </van-action-sheet>
        <!-- 抬头选择 -->
        <van-action-sheet v-model="showInvoiceTitleSelect" title="抬头选择" class="bg-f8" style="height: 600px; font-size: 0.3rem">
            <div
                class="p-1 h-100 w-100 overflow-y"
                style="border-radius: 12px; padding: 10px 16px 20px"
                :style="titleList && titleList.length > 0 ? 'height:300px' : ''"
            >
                <div v-if="titleList && titleList.length > 0">
                    <div v-for="(item, index) in titleList" :key="index" class="mb-2 rounded-15">
                        <van-cell
                            :title="item.invTitle"
                            :label="item.invTitleType == 'PERSONAL' ? '个人抬头' : '企业抬头'"
                            center
                            @click="selectTitle(item)"
                        >
                            <template #default>
                                <span @click.stop="goEditTitle('edit', item)" style="font-size: 14px">编辑</span>
                            </template>
                        </van-cell>
                    </div>
                </div>
                <div v-else>
					<div style="height: 280px;">
						<Noempty :pic="require('@/assets/images/review.png')" :title="'暂无抬头相关信息'" />
					</div>
                </div>
            </div>
			<div class="position-absolute p-1 center-x" style="width: 93%; bottom: 3%">
			    <van-button
			        round
			        block
			        type="info"
			        native-type="submit"
			        :color="themes.color"
			        style="height: 40px; font-size: 16px"
			        @click="goEditTitle('add')"
			    >
			        添加新的抬头
			    </van-button>
			</div>
        </van-action-sheet>
        <!-- 发票内容说明 -->
        <van-action-sheet v-model="showInvoiceContent" title="发票内容说明" class="bg-f8" style="height: 65%">
            <div class="p-1 font-14">
                <ul>
                    <li style="list-style: inside" class="m-1">发票内容将显示详细商品名称与价格信息。</li>
                    <li style="list-style: inside" class="m-1">部分商家可能开具发票内容为商品所属类别及价格信息，如有特殊需求，请向商家客服咨询。</li>
                </ul>
            </div>
        </van-action-sheet>
        <!-- 开票金额说明 -->
        <van-action-sheet v-model="showInvoiceExplain" title="开票金额说明" class="bg-f8" style="height: 65%">
            <div class="p-1 font-14">
                <ul>
                    <li style="list-style: inside" class="m-1">开票金额为消费者实付款金额，红包、优惠、购物券等不在开票范围内。</li>
                    <li style="list-style: inside" class="m-1">如订单发生退货退款，开票金额将变更为最终实付款金额。</li>
                </ul>
            </div>
        </van-action-sheet>
    </div>
</template>

<script>
import { mapState } from 'vuex'
import legendImage from 'components/legendImage/legendImage'
import Noempty from 'components/Noempty/Noempty'
import { invoice } from 'api/invoiceManage'

export default {
    components: {
        legendImage,
        Noempty
    },
    data() {
        return {
            // 获取发票信息
            invoiceInfo: {},
            //抬头信息
            titleInfo: {
                invTitleType: 'PERSONAL'
            },
            //抬头列表
            titleList: [],
            invoiceMoblie: '', //收票人手机
            invoiceEmail: '', //收票人邮箱
            invoiceTypeVal: '', //发票类型标题
            invoiceContent: '', //发票内容
            invoiceType: '', //发票类型 发票类型单选框
            type: 0, //0为付款前 1为付款后申请发票
            isDown: true, //是否下拉
            showInvoiceExplain: false, //开票金额说明
            showInvoiceContent: false, //发票内容说明弹出层
            showInvoiceTitleSelect: false, //抬头选择弹出层
            showInvoiceTypeSelect: false, //发票类型选择弹出层
            arrType: [],
            isLoad: false, //是否请求数据成功
            errorTitle: '' //请求数据错误提示文案
        }
    },
    computed: {
        invTypeTitle() {
            return function (state) {
                const stateText = {
                    ORDINARY_INVOICE: '增值税电子普通发票',
                    VAT_INVOICE: '增值税纸质专用发票',
                    GENERAL_INVOICE: '增值税纸质普通发票'
                }
                return stateText[state]
            }
        },
        ...mapState(['themes'])
    },
    watch: {},
    beforeRouteEnter(to, from, next) {
        // 如果从发票抬头进来 弹出发票弹窗
        if (from.path == '/invoiceTitle') {
            next((vm) => {
                vm.showInvoiceTitleSelectPop()
            })
            return
        }
        next()
    },
    mounted() {
        let invData = null
        if (sessionStorage.getItem('invoiceInfo')) {
            invData = sessionStorage.getItem('invoiceInfo')
        } else if (sessionStorage.getItem('invoice')) {
            invData = sessionStorage.getItem('invoice')
            // 获取后删除
            sessionStorage.removeItem('invoice')
        }
        if (invData) {
            // 如果有缓存数据 读取缓存数据
            this.getSesstionData(invData)
        } else {
            // 没有就发起请求获取数据
            this.getData()
            // 如果有id则是修改发票
            if (this.$route.query.id) {
                this.getDetail()
            }
        }

        this.type = this.$route.query.type //0为付款前 1为付款后申请发票
    },
    methods: {
        // 切换抬头类型时清空
        changeTitleType() {
        },
        // 选择发票抬头
        selectTitle(item) {
            this.titleInfo = item
            this.showInvoiceTitleSelect = false
        },
        // 显示发票抬头选择弹出层
        showInvoiceTitleSelectPop() {
            this.showInvoiceTitleSelect = true
            invoice.getUserInvoiceTitle({invTitleType: this.titleInfo.invTitleType}).then((res) => {
                if (res.status !== 1) {
                    this.$toast(res.msg)
                    return
                }
                this.titleList = res.result
            })
        },
        // 获取缓存数据
        getSesstionData(params) {
            params = JSON.parse(params)
            const addressInfo = JSON.parse(sessionStorage.getItem('addressInfo'))
            sessionStorage.removeItem('addressInfo')
            // 如果有选择地址
            if (addressInfo) {
                this.invoiceInfo.invConsignee = addressInfo.receiver
                this.invoiceInfo.invPhone = addressInfo.mobile
                this.invoiceInfo.invAddress = addressInfo.province + addressInfo.city + addressInfo.area + addressInfo.town + addressInfo.subAdds
            } else {
                this.invoiceInfo = params.invoiceInfo
            }
            this.invoiceMoblie = params.invoiceMoblie
            this.invoiceEmail = params.invoiceEmail
            this.invoiceTypeVal = params.invoiceTypeVal
            this.invoiceType = params.invoiceType
            this.titleInfo = params.titleInfo
            this.arrType = params.arrType
            // 加载数据
            this.isLoad = true
        },
        // 获取发票数据
        getData() {
            const addrId = this.$route.query.addrId ? this.$route.query.addrId : null
            const subNumber = this.$route.query.subNumber ? this.$route.query.subNumber : null
            invoice.getApplyInvoiceInitInfo({ subNumber, addressId: addrId }).then((res) => {
                if (res.status !== 1) {
                    this.errorTitle = res.msg
                    this.$toast(res.msg)
                    return
                }
                this.invoiceInfo = res.result
                this.arrType = res.result.invTypeList
                //回显发票类型
                this.invoiceTypeVal = this.invTypeTitle(res.result.invTypeList[0])
                this.invoiceType = res.result.invTypeList[0]
                this.isLoad = true
                if (res.result.defaultInvoiceTitle) {
                    this.titleInfo = res.result.defaultInvoiceTitle
                }
            })
        },
        //获取开票后的详情信息 修改用
        getDetail() {
            invoice.getInvoiceDetail(this.$route.query.id).then((res) => {
                if (res.status != 1) {
                    this.$toast(res.msg)
                    return
                }
                this.titleInfo.invTitleType = res.result.invTitleType
                this.titleInfo.invTitle = res.result.invTitle
                this.titleInfo.invIdfctMark = res.result.invIdfctMark
                this.titleInfo.invDepositBank = res.result.invDepositBank
                this.titleInfo.invBankAccout = res.result.invBankAccout
                this.titleInfo.invRegAddr = res.result.invRegAddr
                this.titleInfo.invRegPhone = res.result.invRegPhone
                this.invoiceTypeVal = this.invTypeTitle(res.result.invType)
                this.invoiceType = res.result.invType
                if (res.result.invType == 'ORDINARY_INVOICE') {
                    this.invoiceMoblie = res.result.invPhone
                    this.invoiceEmail = res.result.invEmail
                } else {
                    this.invoiceInfo.invConsignee = res.result.invConsignee
                    this.invoiceInfo.invPhone = res.result.invPhone
                    this.invoiceInfo.invAddress = res.result.invAddress
                }
            })
        },
        //去切换地址
        goAddress() {
            this.saveData()
            this.$router.push({
                path: `/addressList`,
                query: {
                    changeAddress: 1,
                    type: 'invoice'
                }
            })
        },
        //缓存数据
        saveData() {
            let params = {}
            params.invoiceMoblie = this.invoiceMoblie
            params.invoiceEmail = this.invoiceEmail
            params.invoiceTypeVal = this.invoiceTypeVal
            params.invoiceType = this.invoiceType
            params.titleInfo = this.titleInfo
            params.invoiceInfo = this.invoiceInfo
            params.arrType = this.arrType
            sessionStorage.setItem('invoice', JSON.stringify(params))
        },
        // 去编辑发票抬头页面
        goEditTitle(type, item) {
            // 存储缓存数据
            this.saveData()
            if (type == 'edit') {
                item = JSON.stringify(item)
                this.$router.push({
                    name: 'invoiceTitle',
                    query: {
                        item: item
                    }
                })
            } else {
                this.$router.push({
                    name: 'invoiceTitle'
                })
            }
        },
        // 选择发票类型
        selectInvoiceType(item) {
            // 回显发票类型
            this.invoiceTypeVal = this.invTypeTitle(item)
            // 发票类型单选框
            this.invoiceType = item
            this.showInvoiceTypeSelect = false
        },
        // 提交
        onSubmit() {
            let params = {}
            const regEmail = /^([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+@([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+\.[a-zA-Z]{2,3}$/ //邮箱验证
            const reg = /^((0\d{2,3}-\d{7,8})|(1([358][0-9]|4[579]|66|7[0135678]|9[89])[0-9]{8}))$/ //手机号验证
            const regPhone = /^(0[0-9]{2,3}\-)([2-9][0-9]{6,7})+(\-[0-9]{1,4})?$/ //座机号码
            const regBankAccout = /^(?:[1-9]{1})(?:\d{15}|\d{18})$/g //银行卡号验证
            // 验证发票抬头
			if (!this.$checkInfo([
			    { type: 'hasValue', value: this.$stringUtils.trim(this.titleInfo.invTitle), msg: '发票抬头不能为空' },
			])) return;
			
			
            // 当发票抬头类型为'企业'时('企业'比'个人或事业单位'多了一个'税号')
            if (this.titleInfo.invTitleType == 'ENTERPRISE') {
				if (!this.$checkInfo([
				    { type: 'hasValue', value: this.$stringUtils.trim(this.titleInfo.invIdfctMark), msg: '税号不能为空' },
				])) return;
            }
			
			// 当选择'增值税电子普通发票'
			if (this.invoiceType == 'ORDINARY_INVOICE') {
				if (!this.$checkInfo([
				    { type: 'hasValue', value: this.$stringUtils.trim(this.invoiceMoblie), msg: '收票人手机不能为空' },
				    { type: 'hasValue', value: this.$stringUtils.trim(this.invoiceEmail), msg: '收票人邮箱不能为空' },
				    { type: 'phone', value: this.invoiceMoblie, msg: '请输入正确的手机号' },
				    { type: 'email', value: this.invoiceEmail, msg: '请输入正确的邮箱' },
				])) return;
			    params.invoiceMoblie = this.invoiceMoblie
			    params.invoiceEmail = this.invoiceEmail
			} else {
				// 当选择'增值税纸质普通发票'或'增值税纸质专用发票'时
				if (!this.$checkInfo([
				    { type: 'hasValue', value: this.invoiceInfo.invAddress, msg: '地址不能为空' },
				])) return;
			}
			
            // 当选择'增值税纸质专用发票'时
            if (this.invoiceType == 'VAT_INVOICE') {
				if (!this.$checkInfo([
				    { type: 'hasValue', value: this.$stringUtils.trim(this.titleInfo.invDepositBank), msg: '开户银行不能为空' },
				    { type: 'hasValue', value: this.$stringUtils.trim(this.titleInfo.invBankAccout), msg: '银行账号不能为空' },
				    { type: 'bankAccount', value: this.titleInfo.invBankAccout, msg: '请输入正确的银行卡号' },
					{ type: 'hasValue', value: this.$stringUtils.trim(this.titleInfo.invRegAddr), msg: '企业地址不能为空' },
					{ type: 'hasValue', value: this.$stringUtils.trim(this.titleInfo.invRegPhone), msg: '企业电话不能为空' },
				])) return;
            }

            params.invoiceTypeVal = this.invoiceTypeVal
            params.invoiceType = this.invoiceType
            params.titleInfo = this.titleInfo
            params.invoiceInfo = this.invoiceInfo
            params.arrType = this.arrType
            // 如果验证通过 则去往确认开具发票页面
            sessionStorage.setItem('invoice', JSON.stringify(params))
            this.$router.push({
                name: 'sumbitInvoice',
                query: {
                    type: this.type,
                    subNumber: this.$route.query.subNumber,
                    id: this.$route.query.id
                }
            })
        },
        //返回
        goback() {
            sessionStorage.removeItem('invoice')
            sessionStorage.removeItem('invoiceInfo')
            this.$router.back()
            this.$router.isBack = true
        },
    }
}
</script>
<style src="@/assets/css/submit-order.css" scoped></style>
<style scoped>
.font-14 {
    font-size: 14px;
}
.invoice .img {
    -webkit-border-radius: 8px !important;
    -moz-border-radius: 8px !important;
    border-radius: 8px !important;
    overflow: hidden;
    transform: translateZ(0);
    width: 60px;
    height: 60px;
}
.van-cell {
    color: #646566;
}
.icon {
    vertical-align: middle;
}
.van-cell__right-icon {
    font-size: 12px;
    margin-left: 8px;
    margin-right: 3px;
}
</style>
